package com.example.tokentest2_7_x.config.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * \* @author: wky
 * \* Date: 2022/10/09
 * \* Time: 17:09
 * \* To change this template use File | Settings | File Templates.
 * \* Description:MyInterceptorConfig2
 * \
 */
//@Configuration
public class MyInterceptorConfig2 implements WebMvcConfigurer {
    @Autowired
    MyInterceptor myInterceptor;

    /**
     * 配置静态资源，避免静态资源请求被拦截
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/templates/**")
                .addResourceLocations("classpath:/templates");
        //super.addResourceHandlers(registry);
    }

    /**
     * 添加拦截器配置
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor)//在这里添加拦截执行类
                //addPathPatterns用于添加拦截规则 /** 代表拦截所有请求
                .addPathPatterns("/**")
                //excludePathPatterns用于排除拦截，即放行
                .excludePathPatterns("/")
                .excludePathPatterns("/userLogin")
                .excludePathPatterns("/static/**")
                .excludePathPatterns("/templates/**");
        //super.addInterceptors(registry);
    }

    /**
     * 解决拦截器上的跨域请求
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                //.allowedOrigins("*")
                .allowedOriginPatterns("*")
                .allowedHeaders(CorsConfiguration.ALL)
                .allowedMethods(CorsConfiguration.ALL)
                .allowCredentials(true)//true
                .maxAge(3600); // 1小时内不需要再预检（发OPTIONS请求）
        //super.addCorsMappings(registry);
    }
}